<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
    <script type="text/javascript" src="js/utils.js"></script>
</head>
<body>
<script type="text/javascript">
    var socket;

    //如果浏览器支持WebSocket
    if(window.WebSocket){
        //参数就是与服务器连接的地址
        var userId="2222";
        socket = new WebSocket("ws://localhost:8888/ws/chat");
        //客户端收到服务器消息的时候就会执行这个回调方法
        socket.onmessage = function (event) {
            console.log(event.data);
            var result = event.data;
            var flagReader = new FileReader();
            flagReader.readAsArrayBuffer(result);
            flagReader.onload = function () {
                var apply = utf8ByteToUnicodeStr(new Int8Array(flagReader.result));
                var parse = JSON.parse(apply);
                var ta = document.getElementById("responseText");
                ta.value = ta.value + "\n"+parse.content;
            }
        };

        //连接建立的回调函数
        socket.onopen = function(event){
            var ta = document.getElementById("responseText");
            ta.value = "连接开启";
            sendConnect();
        };

        function sendConnect(){
            if(!window.WebSocket){
                return;
            }
            //当websocket状态打开
            if(socket.readyState == WebSocket.OPEN){
                var data = {
                    userId: userId,
                    messageType:0
                };
                socket.send(new Blob([JSON.stringify(data)]));
            }else{
                alert("连接没有开启");
            }
        }

        //连接断掉的回调函数
        socket.onclose = function (event) {
            var ta = document.getElementById("responseText");
            ta.value = ta.value +"\n"+"连接关闭";
        }
    }else{
        alert("浏览器不支持WebSocket！");
    }

    //发送数据
    function send(message){
        if(!window.WebSocket){
            return;
        }

        //当websocket状态打开
        if(socket.readyState == WebSocket.OPEN){
            console.log("send....."+message);
            var data = {
                content: message,
                toId: "111",
                type:1,
                chatType:"single",
                messageType:1
            };

            var buffer = new ArrayBuffer(4);
            var dataView = new DataView(buffer);
            dataView.setInt32(0,data.type);

            socket.send(new Blob([buffer,JSON.stringify(data)]));
        }else{
            alert("连接没有开启");
        }
    }
</script>
<form onsubmit="return false">

    <textarea name = "message"></textarea>

    <input type ="button" value="发送数据" onclick="send(this.form.message.value);">
    <br/>

    <h3>服务器输出：</h3>

    <textarea id ="responseText" style="width: 400px;height: 300px;"></textarea>

    <input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="清空数据">
</form>
</body>
</html>